<template>
    <Popup
        ref="popRef"
        :title="props.title"
        width="500px"
        async
        @confirm="submit"
        @close="$emit('close')"
        :confirmLoading="addTeacherLoading"
    >
        <div>
            <el-form
                label-width="90px"
                :model="formData"
                ref="formRef"
                :rules="rules"
                @submit.prevent
            >
                <el-form-item label="教师姓名" prop="id" style="display: none">
                    <el-input placeholder="请输入教师姓名" v-model="formData.id"></el-input>
                </el-form-item>

                <el-form-item
                    label="头像"
                    prop="avatar"
                    v-show="!props?.isSetStatus && !props?.isResetPassword"
                >
                    <el-upload
                        :action="`${config.baseUrl}${config.urlPrefix}/upload/image`"
                        class="avatar-uploader"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        :headers="{
                            token: `${userStore.token}`
                        }"
                        :on-success="uploadSuccess"
                    >
                        <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus></Plus>
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item
                    label="教师姓名"
                    prop="real_name"
                    v-show="!props?.isSetStatus && !props?.isResetPassword"
                >
                    <el-input
                        size="medium"
                        placeholder="请输入教师姓名"
                        v-model="formData.real_name"
                    />
                </el-form-item>
                <el-form-item
                    label="联系方式"
                    prop="phone"
                    v-show="!props?.isSetStatus && !props?.isResetPassword"
                >
                    <el-input placeholder="请输入联系方式" v-model="formData.phone"></el-input>
                </el-form-item>
                <el-form-item
                    label="邮箱"
                    prop="email"
                    v-show="!props?.isSetStatus && !props?.isResetPassword"
                >
                    <el-input placeholder="请输入邮箱" v-model="formData.email"></el-input>
                </el-form-item>
                <el-form-item
                    label="院系/班级"
                    prop="classes_ids"
                    v-show="!props?.isSetStatus && !props?.isResetPassword"
                >
                    <el-cascader
                        style="width: 100%"
                        :options="data"
                        v-model="formData.classes_ids"
                        placeholder="院系/班级"
                        :props="cascaderProps"
                    />
                </el-form-item>
                <el-form-item
                    label="登录密码"
                    prop="password"
                    v-show="!props?.isChange && !props?.isSetStatus"
                >
                    <el-input
                        placeholder="请输入登录密码"
                        type="password"
                        v-model="formData.password"
                        show-password
                    />
                </el-form-item>
                <el-form-item
                    label="确认密码"
                    prop="password_confirm"
                    v-show="!props?.isChange && !props?.isSetStatus"
                >
                    <el-input
                        placeholder="请输入确认密码"
                        type="password"
                        show-password
                        v-model="formData.password_confirm"
                    />
                </el-form-item>

                <el-form-item label="选择状态" v-show="!props?.isChange && !props?.isResetPassword">
                    <el-switch v-model="formData.status"></el-switch>
                </el-form-item>

                <el-form-item
                    label="备注内容"
                    prop="remark"
                    v-show="props?.isSetStatus && !props?.isResetPassword"
                >
                    <el-input
                        size="medium"
                        placeholder="请输入备注内容"
                        v-model="formData.remark"
                        :rows="4"
                        type="textarea"
                        show-word-limit
                    />
                </el-form-item>
            </el-form>
        </div>
    </Popup>
</template>

<script setup lang="ts">
import { addTeacher, editTeacher, uploadImage, getDepartmentList } from '@/api/consumer'
import feedback from '@/utils/feedback'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRequest } from 'vue-hooks-plus'
import config from '@/config'
import useUserStore from '@/stores/modules/user'
const userStore = useUserStore()

const props = withDefaults(
    defineProps<{
        isChange: boolean
        isSetStatus: boolean
        title: string
        isResetPassword: boolean
    }>(),
    {
        isChange: false,
        isSetStatus: false,
        title: '添加/编辑教师',
        isResetPassword: false
    }
)

const cascaderProps = { multiple: true }

interface IFormData {
    avatar: string
    real_name: string
    phone: string
    email: string
    classes_ids: string[]
    password: string
    password_confirm: string
    status: boolean
    remark?: string
}

const emit = defineEmits(['close', 'submit'])

// 获取学院配置
const { data } = useRequest(async () => {
    const _Res = await getDepartmentList({
        page_no: 1,
        page_size: 9999
    })

    const list: any = []

    console.log('_Res_Res_Res',_Res);
    

    _Res?.lists?.forEach((_item) => {
        if (_item?.classes && _item?.classes?.length > 0) {
            list.push({
                value: _item.id,
                label: _item.name,
                children: _item?.classes?.map((_item2) => {
                    return {
                        value: _item2.id,
                        label: _item2.name
                    }
                })
            })
        }
    })

    return list
})

//弹框ref
const popRef = shallowRef()
//表单ref
const formRef = shallowRef<FormInstance>()

//表单数据
const formData: IFormData = reactive({
    avatar: '',
    real_name: '',
    phone: '',
    email: '',
    classes_ids: [],
    password: '',
    password_confirm: '',
    status: true,
    id: '',
    remark: ''
})

const rules = reactive<FormRules<IFormData>>({
    avatar: [
        {
            required: true,
            message: '请选择头像',
            trigger: 'change'
        }
    ],
    real_name: [
        {
            required: true,
            message: '请填写昵称',
            trigger: 'change'
        }
    ],
    phone: [
        {
            required: true,
            message: '请填写手机号码',
            trigger: 'change'
        }
    ],
    email: [
        {
            required: true,
            message: '请填写邮箱号',
            trigger: 'change'
        }
    ],
    classes_ids: [
        {
            required: true,
            message: '请选择班级',
            trigger: 'change'
        }
    ],
    password: [
        {
            required: true,
            message: '请填写密码',
            trigger: 'change'
        }
    ],
    password_confirm: [
        {
            required: true,
            message: '请填写确认密码',
            trigger: 'change'
        }
    ]
})

const { runAsync: addTeacherApi, loading: addTeacherLoading } = useRequest(
    async () => {
        if (!formData.id) {
            return await addTeacher({
                ...formData,
                status: formData.status ? 1 : 2,

                classes_ids: formData.classes_ids
                    ?.map((_item) => {
                        return _item?.[1]
                    })
                    ?.join(',')
            })
        } else {
            return await editTeacher({
                ...formData,
                status: formData.status ? 1 : 2,
                id: formData.id,
                classes_ids: formData.classes_ids
                    ?.map((_item) => {
                        return _item?.[1]
                    })
                    ?.join(',')
            })
        }
    },
    {
        manual: true
    }
)

//提交表单
const submit = async () => {
    await formRef.value?.validate()

    if (formData?.password_confirm != formData?.password) {
        feedback.msgError('两次密码不一致！')
    }

    try {
        await addTeacherApi()

        if (formData.id) {
            feedback.msgSuccess('编辑成功！')
        } else {
            feedback.msgSuccess('新增成功！')
        }

        // popRef.value.close();
        emit('submit')
    } catch (error) {
        console.log('报错了', error)
    }
}

//打开弹框
const open = () => {
    popRef.value.open()
}

const setFormData = async (row: any) => {
    for (const key in formData) {
        if (row[key] != null && row[key] != undefined) {
            //@ts-ignore
            formData[key] = row[key]
        }
    }
}

const beforeAvatarUpload: any = async (rawFile) => {
    console.log('rawFile.type', rawFile.type)

    if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error('请上传图片')
        return false
    }

    return true
}

const uploadSuccess = (_res) => {
    console.log('_res', _res)
    ElMessage({
        message: '上传成功',
        type: 'success'
    })

    if (_res?.data?.uri) {
        formData.avatar = _res?.data?.uri
    }
}

defineExpose({ open, setFormData })
</script>

<style scoped lang="scss"></style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #cccccc;
    width: 120px;
    height: 120px;
    text-align: center;
    font-family: 'Font Awesome 5 Pro Solid', 'Font Awesome 5 Pro Regular', 'Font Awesome 5 Pro',
        sans-serif;
    font-weight: 900;
}

.avatar {
    width: 120px;
    height: 120px;
}
</style>
